package com.firefly.admin.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {
    private static final String REQUEST_HEADER_X_FORWARDED_FOR = "X-Forwarded-For";
    private static final String REQUEST_HEADER_X_REAL_IP = "X-Real-IP";
    private static final String REQUEST_IP_UNKNOWN = "unKnown";

    public static String getLocalIp(HttpServletRequest request) {
        String ip = request.getHeader(REQUEST_HEADER_X_FORWARDED_FOR);
        if (StringUtils.isNotEmpty(ip) && !REQUEST_IP_UNKNOWN.equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(StringPool.COMMA);
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader(REQUEST_HEADER_X_REAL_IP);
        if (StringUtils.isNotEmpty(ip) && !REQUEST_IP_UNKNOWN.equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}
